/*
 * @author hoang.pt
 * @version $Id: ThreadJoin.java 97 2010-08-26 05:28:20Z phantichhoang $
 */

package snippet.theory2;

/**
 * Entity Bath
 * @author hoang.pt
 */
class Bath{
    /**
     * take Bath in minute
     * @param minute
     */
    public synchronized void takeBath(int minute) {
        System.out.println("Bath room is not available in " +minute+ " minutes !!!!!");
        //System.out.println(minute);

        Thread t= Thread.currentThread();
        
        try {
            System.out.println(t.getName()+ " is using the bath. Wait " +minute+ " minutes.");
            Thread.sleep(1000*minute);
        } catch (InterruptedException ex){
            ex.printStackTrace();
        }

        System.out.println("Finish using bathroom.");
        System.out.println("\nAnother.\n");
        System.out.println("\n");
    }
}


/**
 * Thread
 * @author hoang.pt
 */
class BathThread implements Runnable {
    /**
     * minute that thread use
     */
    int minute;

    /**
     * bath entity
     */
    Bath bath;

    /**
     * thread entity
     */
    Thread t;

    /**
     * name of thread
     */
    String name;

    /**
     * constructor
     * @param int minute
     * @param Bath bath
     */
    public BathThread(int minute, Bath bath, String name) {
        this.minute = minute;
        this.bath = bath;
        
        //init target
        this.t= new Thread(this, name);
        t.start();

    }    

    /**
     * Method override
     * @author hoang.pt
     */
    public void run() {
        //System.out.println(t.getName());
        bath.takeBath(minute);
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}

/**
 * Demo Thread join
 * @author hoang.pt
 */
public class ThreadJoin {

    /**
     * Main
     * @author hoang.pt
     * @param String args
     */
    public static void main(String[] args) {
        Bath thienBathroom = new Bath();
        int minute = 2;
        
        BathThread son = new BathThread(minute, thienBathroom, "Son");
        BathThread girl = new BathThread(minute+10, thienBathroom, "Girl");
        BathThread father = new BathThread(minute++, thienBathroom, "Father");

        //Joining thread
        try{
            son.t.join();
            girl.t.join();
            father.t.join();
        } catch(InterruptedException ex) {
            ex.printStackTrace();
        }
    }

}
